package com.sinoglobal.ningxia.activity.shop;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.vip.Login;
import com.sinoglobal.ningxia.beans.GoodsOrderInfoVo;
import com.sinoglobal.ningxia.beans.ShallShopGoodActivityVo;
import com.sinoglobal.ningxia.beans.ShallShopGoodsDataVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.fragment.ShoppingGoodsFragment;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.thread.ItktAsyncTask;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;

import net.tsz.afinal.FinalBitmap;

/**
 * 
 * @author zbl
 * @createdate 2014-6-25 上午10:59:42
 * @Description:精品商城的积分兑换时点击单个item进入此进行积分的兑换
 */
public class ShoppingScoreActivity extends AbstractActivity implements OnClickListener {
	private ImageView shopActivityImg;// 活动的img
	private TextView mallShopGoodsName;// 活动名称
	private TextView mallShopGoodsDate;// 活动的有效期
	private TextView goodsContent;// 活动的详细介绍
	private Button goodsCode;// 活动码
	private String goodsId;
	private Intent intent;
	private ShallShopGoodsDataVo goodsDataVos;// 活动/商品
	private int userScore;
	private int goodScore;
	private final String SCORE = "score";
	private final String REAL_OBJECT="1";//实物
	private int scoreAll = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isTemplate = true;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mallshop_shopping_score);
		titleView.setText(R.string.shoping_itemTitle);
		init();// 初始化控件
		// 商品的ID
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		// score = bundle.getString("score");
		goodsId = bundle.getString("goods_id");
		loadInfo();// 从网络获取数据

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			if (TextUtil.stringIsNotNull(data.getStringExtra(SCORE))) {
				// 兑换实物成功时得到积分
				scoreAll = Integer.parseInt(data.getStringExtra(SCORE));
				setResultToBeforeActivity();
			}
		}
	}

	public void init() {
		shopActivityImg = (ImageView) findViewById(R.id.shopping_img);

		// 设置图片的宽高
		int width = FlyApplication.widthPixels;
		int height = width / 2;
		shopActivityImg.setLayoutParams(new LinearLayout.LayoutParams(width, height));

		mallShopGoodsName = (TextView) findViewById(R.id.mallshop_goodsName);
		mallShopGoodsDate = (TextView) findViewById(R.id.mallshop_goods_date);
		goodsContent = (TextView) findViewById(R.id.goods_content);
		goodsCode = (Button) findViewById(R.id.goods_code);
		goodsCode.setOnClickListener(this);
		templateButtonLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Auto-generated method stub
				setResultToBeforeActivity();
			}
		});
	}

	private void loadInfo() {
		new ItktAsyncTaskWithDialog<Void, Void, ShallShopGoodActivityVo>(getString(R.string.loading), true, true) {

			@Override
			public ShallShopGoodActivityVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getGoodActivityVo("2", goodsId);
			}

			@Override
			public void after(ShallShopGoodActivityVo result) {
				if (result != null) {
					if (Code.CODE_SUCCESS != result.getCode()) {
						Toast.makeText(FlyApplication.context, result.getMessage(), Toast.LENGTH_SHORT).show();
					} else {
						// 从服务器上获取数据填充在布局文件上
						goodsDataVos = result.getEnentsDataVo();
						FinalBitmap fb = FinalBitmap.create(ShoppingScoreActivity.this);
						fb.configLoadfailImage(R.drawable.default21);
						fb.configLoadingImage(R.drawable.default21);
						String URL = ConnectionUtil.localUrl + goodsDataVos.getGoods_img();

						fb.display(shopActivityImg, URL);

						mallShopGoodsName.setText(goodsDataVos.getGoods_name());
						// 对于有效日期经行处理
						mallShopGoodsDate.requestFocus();// 需要焦点
						mallShopGoodsDate.setText(goodsDataVos.getGoods_start() + "至" + goodsDataVos.getGoods_end());
						goodsContent.setText(goodsDataVos.getConten());

					}
				}

			}

			@Override
			public void exception() {

			}
		}.execute();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.goods_code:// 点击进入购买实物或者领取活动码
			// 判断是用户是否登录
			if (TextUtil.stringIsNotNull(FlyApplication.userId)) {
				//
				goodsCode.setClickable(false);

				// 获取用户的积分数和商品的积分
				String score = SharedPreferenceUtil.getString(FlyApplication.context, SCORE);

				userScore = Integer.parseInt(score);
				goodScore = Integer.parseInt(goodsDataVos.getScore());
				ItktLog.e("**----------userScore----------------------------" + userScore
						+ "**----------goodScore----------------------------" + goodScore);
				// 判断用户的的积分是否大于商品的积分
				if (userScore >= goodScore) {
					// 判断是实体物品还是活动，实物就转到填写个人信息页，活动的话返回一个活动码
					if (REAL_OBJECT.equals(goodsDataVos.getType2())) {
						intent = new Intent(this, PurchaseGoodsActivity.class);
						intent.putExtra("goods_id", goodsId);// 商品的id
						intent.putExtra("type", goodsDataVos.getType());// 1现金 2积分
						intent.putExtra("type2", goodsDataVos.getType2());// 1实物 2活动
						startActivityForResult(intent, 1);
						goodsCode.setClickable(true);
					} else {
						// 访问网络获取活动码802
						new ItktAsyncTask<Void, Void, GoodsOrderInfoVo>() {

							@Override
							public GoodsOrderInfoVo before(Void... params) throws Exception {

								return RemoteImpl.getInstance().getGoodsOrderInfoVo(goodsDataVos.getType(), goodsDataVos.getType2(),
										goodsId);
							}

							@Override
							public void after(GoodsOrderInfoVo result) {
								// 获取结果显示在btn上，并设置btn不能再点击
								if (result != null) {
									if (Code.CODE_SUCCESS == result.getCode()) {
										scoreAll = Integer.parseInt(result.getMyscore());
										// 将积分减去
										// userScore -= goodScore;
										// SharedPreferenceUtil.saveString(ShoppingScoreActivity.this,
										// "score", userScore + "");
										// LogUtil.e("@@--------------new----------@@"+
										// SharedPreferenceUtil.getString(FlyApplication.context,
										// "score"));
										goodsCode.setText(result.getGoods_code());
										goodsCode.setBackgroundResource(R.drawable.bg_enentitem_btn);
										goodsCode.setClickable(false);

									} else if (3 == result.getCode()) {
										ShoppingGoodsFragment selectDialog = new ShoppingGoodsFragment(ShoppingScoreActivity.this,
												R.style.dialog);// 创建Dialog并设置样式主题
										selectDialog.setCanceledOnTouchOutside(false);// 设置点击Dialog外部任意区域关闭Dialog
										selectDialog.show();
										goodsCode.setClickable(true);
									}

									else {
										showShortToastMessage(result.getMessage());
									}
								}

							}

							@Override
							public void exception() {
								goodsCode.setClickable(true);
							}
						}.execute();

					}

				} else {
					// 提示用户积分不够，不能进行购买
					ShoppingGoodsFragment selectDialog = new ShoppingGoodsFragment(this, R.style.dialog);// 创建Dialog并设置样式主题
					selectDialog.setCanceledOnTouchOutside(false);// 设置点击Dialog外部任意区域关闭Dialog
					selectDialog.show();
					goodsCode.setClickable(true);
				}
			} else {
				intent = new Intent(this, Login.class);
				startActivityForResult(intent, 0);
			}
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResultToBeforeActivity();

		}
		return true;
	}

	private void setResultToBeforeActivity() {
		Intent intent = getIntent();
		if (scoreAll != -1) {
			intent.putExtra(SCORE, String.valueOf(scoreAll));
		}
		setResult(0, intent);
		finish();
	}

	@Override
	protected void onDestroy() {
		// Auto-generated method stub
		super.onDestroy();
	}
}
